package com.tongtech.system.service.impl;

import com.tongtech.common.core.constant.UserConstants;
import com.tongtech.common.core.exception.ServiceException;
import com.tongtech.common.core.text.Convert;
import com.tongtech.common.core.utils.SpringUtils;
import com.tongtech.common.core.utils.StringUtils;
import com.tongtech.common.datascope.annotation.DataScope;
import com.tongtech.system.domain.Industry;
import com.tongtech.system.domain.vo.IndustryTreeSelect;
import com.tongtech.system.mapper.IndustryMapper;
import com.tongtech.system.service.IIndustryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 行业管理 服务实现
 *
 * @author xingyc
 */
@Service
public class IndustryServiceImpl implements IIndustryService
{
    @Autowired
    private IndustryMapper industryMapper;

    /**
     * 查询行业管理数据
     *
     * @param industry 行业信息
     * @return 行业信息集合
     */
    @Override
    @DataScope(deptAlias = "industry")
    public List<Industry> selectIndustryList(Industry industry)
    {
        return industryMapper.selectIndustryList(industry);
    }

    /**
     * 查询行业树结构信息
     *
     * @param industry 行业信息
     * @return 行业树信息集合
     */
    @Override
    public List<IndustryTreeSelect> selectIndustryTreeList(Industry industry)
    {
        List<Industry> industrys = SpringUtils.getAopProxy(this).selectIndustryList(industry);
        return buildIndustryTreeSelect(industrys);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param industrys 行业列表
     * @return 树结构列表
     */
    @Override
    public List<Industry> buildIndustryTree(List<Industry> industrys)
    {
        List<Industry> returnList = new ArrayList<Industry>();
        List<Long> tempList = industrys.stream().map(Industry::getIndustryId).collect(Collectors.toList());
        for (Industry industry : industrys)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(industry.getParentId()))
            {
                recursionFn(industrys, industry);
                returnList.add(industry);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = industrys;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param industrys 行业列表
     * @return 下拉树结构列表
     */
    @Override
    public List<IndustryTreeSelect> buildIndustryTreeSelect(List<Industry> industrys)
    {
        List<Industry> deptTrees = buildIndustryTree(industrys);
        return deptTrees.stream().map(IndustryTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据行业ID查询信息
     *
     * @param industryId 行业ID
     * @return 行业信息
     */
    @Override
    public Industry selectIndustryById(Long industryId)
    {
        return industryMapper.selectIndustryById(industryId);
    }

    /**
     * 根据ID查询所有子行业（正常状态）
     *
     * @param industryId 行业ID
     * @return 子行业数
     */
    @Override
    public int selectNormalChildrenIndustryById(Long industryId)
    {
        return industryMapper.selectNormalChildrenIndustryById(industryId);
    }

    /**
     * 是否存在子节点
     *
     * @param industryId 行业ID
     * @return 结果
     */
    @Override
    public boolean hasChildByIndustryId(Long industryId)
    {
        int result = industryMapper.hasChildByIndustryId(industryId);
        return result > 0;
    }


    /**
     * 校验行业名称是否唯一
     *
     * @param industry 行业信息
     * @return 结果
     */
    @Override
    public boolean checkIndustryNameUnique(Industry industry)
    {
        Long deptId = StringUtils.isNull(industry.getIndustryId()) ? -1L : industry.getIndustryId();
        Industry info = industryMapper.checkIndustryNameUnique(industry.getIndustryName(), industry.getParentId());
        if (StringUtils.isNotNull(info) && info.getIndustryId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存行业信息
     *
     * @param industry 行业信息
     * @return 结果
     */
    @Override
    public int insertIndustry(Industry industry)
    {
        Industry info = industryMapper.selectIndustryById(industry.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("行业停用，不允许新增");
        }
        industry.setAncestors(info.getAncestors() + "," + industry.getParentId());
        return industryMapper.insertIndustry(industry);
    }

    /**
     * 修改保存行业信息
     *
     * @param industry 行业信息
     * @return 结果
     */
    @Override
    public int updateIndustry(Industry industry)
    {
        Industry newParentIndustry = industryMapper.selectIndustryById(industry.getParentId());
        Industry oldIndustry = industryMapper.selectIndustryById(industry.getIndustryId());
        if (StringUtils.isNotNull(newParentIndustry) && StringUtils.isNotNull(oldIndustry))
        {
            String newAncestors = newParentIndustry.getAncestors() + "," + newParentIndustry.getIndustryId();
            String oldAncestors = oldIndustry.getAncestors();
            industry.setAncestors(newAncestors);
            updateIndustryChildren(industry.getIndustryId(), newAncestors, oldAncestors);
        }
        int result = industryMapper.updateIndustry(industry);
        if (UserConstants.DEPT_NORMAL.equals(industry.getStatus()) && StringUtils.isNotEmpty(industry.getAncestors())
                && !StringUtils.equals("0", industry.getAncestors()))
        {
            // 如果该行业是启用状态，则启用该行业的所有上级行业
            updateParentIndustryStatusNormal(industry);
        }
        return result;
    }

    /**
     * 修改该行业的父级行业状态
     *
     * @param industry 当前行业
     */
    private void updateParentIndustryStatusNormal(Industry industry)
    {
        String ancestors = industry.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        industryMapper.updateIndustryStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param industryId 被修改的行业ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateIndustryChildren(Long industryId, String newAncestors, String oldAncestors)
    {
        List<Industry> children = industryMapper.selectChildrenIndustryById(industryId);
        for (Industry child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            industryMapper.updateIndustryChildren(children);
        }
    }

    /**
     * 删除行业管理信息
     *
     * @param deptId 行业ID
     * @return 结果
     */
    @Override
    public int deleteIndustryById(Long deptId)
    {
        return industryMapper.deleteIndustryById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Industry> list, Industry t)
    {
        // 得到子节点列表
        List<Industry> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Industry tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Industry> getChildList(List<Industry> list, Industry t)
    {
        List<Industry> tlist = new ArrayList<Industry>();
        Iterator<Industry> it = list.iterator();
        while (it.hasNext())
        {
            Industry n = (Industry) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getIndustryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Industry> list, Industry t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
